<?php

namespace Modules\Custessa;

use APP;
use Core\CModule as CModule;
use CController as CAction;
use CWidgetConfig;
use Modules\Custessa\Helpers\Assets;
use Modules\Custessa\Services\WidgetRegistry;
use Modules\Custessa\Services\WidgetConfig;

class Module extends CModule {

	const LEGACY_ACTIONS = [
		'actionconf.php', 'auditacts.php', 'browserwarning.php', 'disc_prototypes.php', 'graphs.php', 'history.php',
		'host_discovery.php', 'host_prototypes.php', 'hostgroups.php', 'hostinventories.php',
		'hostinventoriesoverview.php', 'httpconf.php', 'httpdetails.php', 'image.php', 'imgstore.php', 'index.php',
		'items.php', 'maintenance.php', 'map.php', 'report2.php', 'report4.php', 'sysmap.php', 'sysmaps.php',
		'templates.php', 'toptriggers.php', 'tr_events.php', 'trigger_prototypes.php', 'triggers.php'
	];

	public function init(): void {
		Assets::css('custessa:style', '');
		// $this->createWidgetRegistry();
		// $this->bindWidgetConfig();
	}

	 /**
	 * Before action event handler.
	 *
	 * @param CAction $action    Current request handler object.
	 */
	public function onBeforeAction(CAction $action): void {
	}

	/**
	 * Before terminate event handler.
	 */
	public function onTerminate(CAction $action): void {
		if (!in_array($action->getAction(), static::LEGACY_ACTIONS)) {
			$router = APP::Component()->get('router');

			if ($router->getLayout() !== 'layout.htmlpage' || $router->getView() === null) {
				return;
			}
		}

		echo Assets::getHtmlTags();
	}

	/**
	 * Register widget registry as global accessible component 'widgets'.
	 */
	protected function createWidgetRegistry() {
		APP::Component()->widgets = new WidgetRegistry;
	}

	/**
	 * Enables CWidgetConfig intercepting to enable custom widgets support.
	 */
	protected function bindWidgetConfig() {
		class_alias(WidgetConfig::class, CWidgetConfig::class);
	}
}
